package com.isb.emailclient.db;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import com.isb.emailclient.model.Account;

public class DBMailManager {

	private static final String TAG = DBMailManager.class.getSimpleName();
	private SQLiteDatabase database;
	private SQLiteHelper dbHelper;

	private String[] allAccountColumns = { SQLiteHelper.KEY_ID,
			SQLiteHelper.EMAIL, SQLiteHelper.PASSWORD };

	private String[] allFolderColumns = { SQLiteHelper.KEY_ID,
			SQLiteHelper.FOLDER_NAME, SQLiteHelper.ACCOUNT_ID };

	private String[] allMailColumns = { SQLiteHelper.KEY_ID,
			SQLiteHelper.MAIL_NUMBER, SQLiteHelper.FOLDER_ID, 
			SQLiteHelper.FROM_ADDR, SQLiteHelper.TO_ADDR,
			SQLiteHelper.SUBJECT, SQLiteHelper.CONTENT,
			SQLiteHelper.DATE_TIME};

	private String[] allAttachmentColumns = { SQLiteHelper.KEY_ID,
			SQLiteHelper.MAIL_ID, SQLiteHelper.FILE_NAME };

	public DBMailManager(Context ctx) {
		dbHelper = new SQLiteHelper(ctx);
	}

	public void open() throws SQLException {
		database = dbHelper.getWritableDatabase();
	}

	public void close() {
		dbHelper.close();
	}

	public Account createAccount(String email, String password) {
		ContentValues values = new ContentValues();
		values.put(SQLiteHelper.EMAIL, email);
		values.put(SQLiteHelper.PASSWORD, password);
		long insertId = database.insert(SQLiteHelper.TABLE_ACCOUNT, null,
				values);
		Cursor cursor = database.query(SQLiteHelper.TABLE_ACCOUNT,
				allAccountColumns, SQLiteHelper.KEY_ID + " = " + insertId,
				null, null, null, null);
		cursor.moveToFirst();

		Account newAccount = cursorToAccount(cursor);
		cursor.close();
		return newAccount;
	}

	
	public void deleteAccount(Account account) {
		int id = account.getId();
		database.delete(SQLiteHelper.TABLE_ACCOUNT, SQLiteHelper.KEY_ID  + " + " + id,
				null);
	}
	
	
	public List<Account> getAllAccount() {
		List<Account> accounts = new ArrayList<Account>();
		
		Cursor cursor = database.query(SQLiteHelper.TABLE_ACCOUNT, allAccountColumns, null, null, null, null, null);
		cursor.moveToFirst();
		while (!cursor.isAfterLast()) {
			Account account = cursorToAccount(cursor);
			accounts.add(account);
			cursor.moveToNext();
		}
		
		cursor.close();
		return accounts;
	}
	
	private Account cursorToAccount(Cursor cursor) {
		// Log.i(TAG, cursor.getCount() + "");
		
		Account account = new Account();
		account.setId(cursor.getInt(0));
		account.setEmail(cursor.getString(1));
		account.setPassword(cursor.getString(2));
		return account;
	}

}
